package com.demo.oshi;

import oshi.SystemInfo;
import oshi.hardware.*;
import oshi.software.os.FileSystem;
import oshi.software.os.NetworkParams;
import oshi.software.os.OSFileStore;
import oshi.util.FormatUtil;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class ShiMainRun {
    public static void main(String[] args) throws InterruptedException {
        printCpuinfo();
        printMemInfo();
        printSysInfo();
        printJvmInfo();
        printThread();
        printDisks();
        printFileSystem();
        printNetworkInterfaces();
        printNetworkParameters();
        printDisplays();
        printUsbDevices();
    }

    private static void printCpuinfo() throws InterruptedException {
        //System.out.println("----------------cpu信息----------------");
        SystemInfo systemInfo = new SystemInfo();
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        // 睡眠1s
        TimeUnit.SECONDS.sleep(1);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        System.out.println("----------------cpu信息----------------");
        System.out.println("cpu核数:" + processor.getLogicalProcessorCount());
        System.out.println("cpu系统使用率:" + new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        System.out.println("cpu用户使用率:" + new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        System.out.println("cpu当前等待率:" + new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        System.out.println("cpu当前使用率:" + new DecimalFormat("#.##%").format(1.0-(idle * 1.0 / totalCpu)));

    }
    public static void printMemInfo(){
        System.out.println("----------------主机内存信息----------------");
        SystemInfo systemInfo = new SystemInfo();
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        //总内存
        long totalByte = memory.getTotal();
        //剩余
        long acaliableByte = memory.getAvailable();
        System.out.println("总内存 = " + formatByte(totalByte));
        System.out.println("使用" + formatByte(totalByte-acaliableByte));
        System.out.println("剩余内存 = " + formatByte(acaliableByte));
        System.out.println("使用率：" + new DecimalFormat("#.##%").format((totalByte-acaliableByte)*1.0/totalByte));
    }

    public static void printSysInfo(){
        System.out.println("----------------操作系统信息----------------");
        Properties props = System.getProperties();
        //系统名称
        String osName = props.getProperty("os.name");
        //架构名称
        String osArch = props.getProperty("os.arch");
        System.out.println("操作系统名 = " + osName);
        System.out.println("系统架构 = " + osArch);
    }

    public static void printJvmInfo(){
        System.out.println("----------------jvm信息----------------");
        Properties props = System.getProperties();
        Runtime runtime = Runtime.getRuntime();
        //jvm总内存
        long jvmTotalMemoryByte = runtime.totalMemory();
        //jvm最大可申请
        long jvmMaxMoryByte = runtime.maxMemory();
        //空闲空间
        long freeMemoryByte = runtime.freeMemory();
        //jdk版本
        String jdkVersion = props.getProperty("java.version");
        //jdk路径
        String jdkHome = props.getProperty("java.home");
        System.out.println("jvm内存总量 = " + formatByte(jvmTotalMemoryByte));
        System.out.println("jvm已使用内存 = " + formatByte(jvmTotalMemoryByte-freeMemoryByte));
        System.out.println("jvm剩余内存 = " + formatByte(freeMemoryByte));
        System.out.println("jvm内存使用率 = " + new DecimalFormat("#.##%").format((jvmTotalMemoryByte-freeMemoryByte)*1.0/jvmTotalMemoryByte));
        System.out.println("java版本 = " + jdkVersion);
        //System.out.println("jdkHome = " + jdkHome);
    }

    public static void printThread(){
        System.out.println("----------------线程信息----------------");
        ThreadGroup currentGroup =Thread.currentThread().getThreadGroup();

        while (currentGroup.getParent()!=null){
            // 返回此线程组的父线程组
            currentGroup=currentGroup.getParent();
        }
        //此线程组中活动线程的估计数
        int noThreads = currentGroup.activeCount();

        Thread[] lstThreads = new Thread[noThreads];
        //把对此线程组中的所有活动子组的引用复制到指定数组中。
        currentGroup.enumerate(lstThreads);
        for (Thread thread : lstThreads) {
            System.out.println("线程数量："+noThreads+" 线程id：" + thread.getId() + " 线程名称：" + thread.getName() + " 线程状态：" + thread.getState());
        }
    }
    private static void printDisks() {
        System.out.println("----------------磁盘信息----------------");
        List<HWDiskStore> diskStores = new SystemInfo().getHardware().getDiskStores();

        System.out.println("Disks:");

        for (HWDiskStore disk : diskStores) {

            boolean readwrite = disk.getReads() > 0 || disk.getWrites() > 0;

            System.out.format(" %s: (model: %s - S/N: %s) size: %s, reads: %s (%s), writes: %s (%s), xfer: %s ms%n",

                    disk.getName(), disk.getModel(), disk.getSerial(),

                    disk.getSize() > 0 ? FormatUtil.formatBytesDecimal(disk.getSize()) : "?",

                    readwrite ? disk.getReads() : "?", readwrite ? FormatUtil.formatBytes(disk.getReadBytes()) : "?",

                    readwrite ? disk.getWrites() : "?", readwrite ? FormatUtil.formatBytes(disk.getWriteBytes()) : "?",

                    readwrite ? disk.getTransferTime() : "?");

            List<HWPartition> partitions = disk.getPartitions();

            if (partitions == null) {

                // TODO Remove when all OS's implemented

                continue;

            }

            for (HWPartition part : partitions) {

                System.out.format(" |-- %s: %s (%s) Maj:Min=%d:%d, size: %s%s%n", part.getIdentification(),

                        part.getName(), part.getType(), part.getMajor(), part.getMinor(),

                        FormatUtil.formatBytesDecimal(part.getSize()),

                        part.getMountPoint().isEmpty() ? "" : " @ " + part.getMountPoint());

            }

        }

    }

    private static void printFileSystem() {
        System.out.println("----------------文件系统----------------");
        FileSystem fileSystem = new SystemInfo().getOperatingSystem().getFileSystem();

        System.out.println("File System:");

        System.out.format(" File Descriptors: %d/%d%n", fileSystem.getOpenFileDescriptors(),

                fileSystem.getMaxFileDescriptors());

        List<OSFileStore> fsArray = fileSystem.getFileStores();

        for (OSFileStore fs : fsArray) {

            long usable = fs.getUsableSpace();

            long total = fs.getTotalSpace();

            System.out.format(

                    " %s (%s) [%s] %s of %s free (%.1f%%) is %s "

                            + (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s")

                            + " and is mounted at %s%n",

                    fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(),

                    FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total,

                    fs.getVolume(), fs.getLogicalVolume(), fs.getMount());

        }

    }

    private static void printNetworkInterfaces() {
        System.out.println("----------------网络接口----------------");
        List<NetworkIF> networkIFs = new SystemInfo().getHardware().getNetworkIFs();

        System.out.println("Network interfaces:");

        for (NetworkIF net : networkIFs) {

            System.out.format(" Name: %s (%s)%n", net.getName(), net.getDisplayName());

            System.out.format("   MAC Address: %s %n", net.getMacaddr());

            System.out.format("   MTU: %s, Speed: %s %n", net.getMTU(), FormatUtil.formatValue(net.getSpeed(), "bps"));

            System.out.format("   IPv4: %s %n", Arrays.toString(net.getIPv4addr()));

            System.out.format("   IPv6: %s %n", Arrays.toString(net.getIPv6addr()));

            boolean hasData = net.getBytesRecv() > 0 || net.getBytesSent() > 0 || net.getPacketsRecv() > 0

                    || net.getPacketsSent() > 0;

            System.out.format("   Traffic: received %s/%s%s; transmitted %s/%s%s %n",

                    hasData ? net.getPacketsRecv() + " packets" : "?",

                    hasData ? FormatUtil.formatBytes(net.getBytesRecv()) : "?",

                    hasData ? " (" + net.getInErrors() + " err)" : "",

                    hasData ? net.getPacketsSent() + " packets" : "?",

                    hasData ? FormatUtil.formatBytes(net.getBytesSent()) : "?",

                    hasData ? " (" + net.getOutErrors() + " err)" : "");

        }

    }

    private static void printNetworkParameters() {
        System.out.println("----------------网络信息----------------");
        NetworkParams networkParams = new SystemInfo().getOperatingSystem().getNetworkParams();

        System.out.println("Network parameters:");

        System.out.format(" Host name: %s%n", networkParams.getHostName());

        System.out.format(" Domain name: %s%n", networkParams.getDomainName());

        System.out.format(" DNS servers: %s%n", Arrays.toString(networkParams.getDnsServers()));

        System.out.format(" IPv4 Gateway: %s%n", networkParams.getIpv4DefaultGateway());

        System.out.format(" IPv6 Gateway: %s%n", networkParams.getIpv6DefaultGateway());

    }

    private static void printDisplays() {
        System.out.println("----------------显示设备----------------");
        List<Display> displays = new SystemInfo().getHardware().getDisplays();
        System.out.println("Displays:");

        int i = 0;

        for (Display display : displays) {

            System.out.println(" Display " + i + ":");

            System.out.println(display.toString());

            i++;

        }

    }

    private static void printUsbDevices() {
        System.out.println("----------------USB设备信息----------------");
        List<UsbDevice> usbDevices = new SystemInfo().getHardware().getUsbDevices(true);

        System.out.println("USB Devices:");

        for (UsbDevice usbDevice : usbDevices) {

            System.out.println(usbDevice.toString());

        }

    }


    public static String formatByte(long byteNumber){
        //换算单位
        double FORMAT = 1024.0;
        double kbNumber = byteNumber/FORMAT;
        if(kbNumber<FORMAT){
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber/FORMAT;
        if(mbNumber<FORMAT){
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber/FORMAT;
        if(gbNumber<FORMAT){
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber/FORMAT;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }
}
